package com.census.database;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public abstract class DBManager {
	private static Properties properties=new Properties();
	static{
		InputStream is=DBManager.class.getClassLoader().getResourceAsStream("db.properties");
		try {
			properties.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	static{
		try {
			Class.forName(properties.getProperty("connection.driverClass"));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public Connection openConnection() throws SQLException{
		String url=properties.getProperty("connection.url");
		String userName=properties.getProperty("connection.username");
		String userPwd=properties.getProperty("connection.password");
		return DriverManager.getConnection(url, userName,userPwd);
	}
	
	public int update(Connection conn,String sql,Object...obs)throws SQLException{
		int count=0;
		if(conn!=null && !conn.isClosed()){
			PreparedStatement psment=conn.prepareStatement(sql);
			if(obs!=null){
				for (int i = 0; i < obs.length; i++) {
					psment.setObject(i+1, obs[i]);
				}
			}
			count=psment.executeUpdate();
		}
		return count;
	}
	
	public ResultSet query(Connection conn,String sql,Object...obs)throws SQLException{
		ResultSet rs=null;
		if(conn!=null && !conn.isClosed()){
			PreparedStatement psment=conn.prepareStatement(sql);
			if(obs!=null){
				for (int i = 0; i < obs.length; i++) {
					psment.setObject(i+1, obs[i]);
				}
			}
			rs=psment.executeQuery();
		}
		return rs;
	}
	public void closeConnection(Connection conn)throws SQLException{
		if(conn!=null && !conn.isClosed()){
			conn.close();
			conn=null;
		}
	}
}